package com.ztesoft.bss.base.util;

import com.alibaba.fastjson.JSONObject;
import com.iwhalecloud.bss.kite.client.vo.scene.CommonAttrVO;
import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.constant.ServiceOfferConsts;
import com.iwhalecloud.bss.kite.common.util.KiteDateUtils;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteMapUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.client.api.inf.IInfServiceBus;
import com.iwhalecloud.bss.kite.cucc.client.dto.attr.UnicomRegion;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalServiceOfferConsts;
import com.iwhalecloud.bss.kite.cucc.common.util.CommonUtil;
import com.iwhalecloud.bss.kite.cucc.common.util.DateFormatUtils;
import com.iwhalecloud.bss.kite.cucc.dataservice.cache.UnicomRegionCache;
import com.iwhalecloud.bss.kite.dataservice.cache.DcPublicCache;
import com.iwhalecloud.bss.kite.dataservice.entity.DcPublic;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttrValue;
import com.iwhalecloud.bss.kite.manager.inst.KiteProdInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteSceneInst;
import com.ztesoft.bss.common.util.ContextUtil;
import com.ztesoft.bss.common.util.SpringUtil;
import com.ztesoft.common.logger.api.ZLogger;
import com.ztesoft.common.logger.factory.ZLoggerFactory;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

public class LocalAttrUtils {

    private static final ZLogger LOGGER = ZLoggerFactory.getLogger(LocalAttrUtils.class, KeyConsts.LOG_MODULE);

    @Autowired
    private IInfServiceBus infServiceBus;

    public static final String SDH_CONDITION = "2_0000220,2_0000107";//SDH
    public static final String CMNET_CONDITION = "2_0000220";//互联网
    public static final String LOCAL_PROD = "10002183,10002187,10002174,10002176,10002224";//本地
    public static final String GJ_PROD = "60040444,60040446,60040447";//国际

    public static LocalAttrUtils getInstance(){
        return new LocalAttrUtils();
    }

    /**
     * 跨域判断
     *    销售中心跨域流程优化需求，2021-12-22版本，跨域规则：
     *    互联网专线：受理人员工号归属省份与装机地址省份不一致
     *    以太网/SDH/光纤出租：受理人员工号归属省份、A端装机地址省份、Z端装机地址省份，任意两个归属省份不一致，则认为是跨域，其他场景则为非跨域
     *    MPLS-VPN：PE归属网络取值为全国则为跨域，取值为省内则为非跨域
     */
    public static boolean isCrossDomain(KiteSceneInst kiteSceneInst, KiteProdInst prodInst) {
        /*国际商品默认跨域*/
        if(GJ_PROD.contains(prodInst.getProdId())){
            return true;
        }
        String provinceNbr = ContextUtil.getLoginInfo().getUserInfo().getPostProvinceNbr();

        // SDH/以太网/光纤出租
        if(KiteStringUtils.equalsAny(prodInst.getProdId(), "10002385","10002384","10002176","10002174","10002387","10002386","10002187","10002183","10002230")) {
            // 受理人员工号归属省份、A端装机地址省份、Z端装机地址省份，任意两个归属省份不一致，则认为是跨域，其他场景则为非跨域
            String provinceA = prodInst.getAttrValue("2_0000220");
            String provinceZ = prodInst.getAttrValue("2_0000107");

            if((!KiteStringUtils.isEqual(provinceNbr, provinceA) && !KiteStringUtils.isAnyEmpty(provinceNbr, provinceA)) ||
                (!KiteStringUtils.isEqual(provinceNbr, provinceZ) && !KiteStringUtils.isAnyEmpty(provinceNbr, provinceZ)) ||
                (!KiteStringUtils.isEqual(provinceA, provinceZ) && !KiteStringUtils.isAnyEmpty(provinceA, provinceZ))) {
                return true;
            }
        }

        // 互联网专线
        if(KiteStringUtils.isEqual(prodInst.getProdId(), "10002224")) {
            // 受理人员工号归属省份与装机地址省份不一致，则认为是跨域
            String provinceA = prodInst.getAttrValue("2_0000220");
            if(!KiteStringUtils.isEqual(provinceNbr, provinceA) && !KiteStringUtils.isAnyEmpty(provinceNbr, provinceA)) {
                return true;
            }
        }

        // MPLS-VPN
        if(KiteStringUtils.isEqual(prodInst.getProdId(), "10003665")) {
            // PE归属网络取值为全国则为跨域，取值为省内则为非跨域
            String peHplmn = prodInst.getAttrValue("2_0000048");
            if(KiteStringUtils.isEqual(peHplmn, "1_0000222")) {
                return true;
            }
        }

        /*
         * 原跨域判断逻辑
         if (null != prodInst.getAttr(SDH_CONDITION.split(",")[0]) && null != prodInst.getAttr(SDH_CONDITION.split(",")[1])) {
            String a = prodInst.getAttr(SDH_CONDITION.split(",")[0]).getValue();
            String z = prodInst.getAttr(SDH_CONDITION.split(",")[1]).getValue();
            if(!a.isEmpty()&&!z.isEmpty()){
                if (!provinceNbr.equals(a) || !provinceNbr.equals(z) || !a.equals(z)) {
                    return true;
                }
            }
        }
        if(null!= prodInst.getAttr(CMNET_CONDITION)&&null == prodInst.getAttr(SDH_CONDITION.split(",")[1])){
            String address=prodInst.getAttr(CMNET_CONDITION).getValue();
            if(!address.equals(provinceNbr)){
                return true;
            }
        }*/
        return false;
    }

    /*
     * 跨域判断（产品变更，SDH、以太网、互联网专线 跨域业务不能进行停开机操作判断使用）
     *    互联网专线：受理人员工号归属省份与装机地址省份不一致
     *    以太网/SDH：受理人员工号归属省份、A端装机地址省份、Z端装机地址省份，任意两个归属省份不一致，则认为是跨域，其他场景则为非跨域
     */
    public static boolean isCrossDomainForUserDetail(String cateId, Map<String,Object> userDetailMap) {
        List<Map> userServiceInfos = CommonUtil.getList(userDetailMap, "USER_SERVICE_INFOS");
        if(KiteListUtils.isNotEmpty(userServiceInfos)) {
            String provinceA = null;
            String provinceZ = null;
            for(Map userServiceInfo: userServiceInfos) {
                List<Map<String,Object>> userServiceItemInfos = CommonUtil.getList(userServiceInfo, "USER_SERVICE_ITEM_INFOS");
                if(KiteListUtils.isEmpty(userServiceItemInfos)) {
                    continue;
                }
                Map<String,Object> aProvinceAttr = userServiceItemInfos.stream().filter(userServiceitemInfo ->
                    KiteStringUtils.equals("2_0000220", KiteMapUtils.getString(userServiceitemInfo, "CRM_ATTR_CODE"))).findFirst().orElse(null);
                provinceA = KiteMapUtils.getString(aProvinceAttr, "CRM_ATTR_VALUE");
                Map<String,Object> zProvinceAttr = userServiceItemInfos.stream().filter(userServiceitemInfo ->
                    KiteStringUtils.equals("2_0000107", KiteMapUtils.getString(userServiceitemInfo, "CRM_ATTR_CODE"))).findFirst().orElse(null);
                provinceZ = KiteMapUtils.getString(zProvinceAttr, "CRM_ATTR_VALUE");
            }
            // 获取业务受理工号归属
            String provinceNbr = ContextUtil.getLoginInfo().getUserInfo().getPostProvinceNbr();

            // SDH/以太网，受理人员工号归属省份、A端装机地址省份、Z端装机地址省份，任意两个归属省份不一致，则认为是跨域，其他场景则为非跨域
            if(KiteStringUtils.equalsAny(cateId, "2004023","2004022","2004021","2004020","2004034","2004033","2004032","2004031")) {
                if((!KiteStringUtils.isEqual(provinceNbr, provinceA) && !KiteStringUtils.isAnyEmpty(provinceNbr, provinceA)) ||
                    (!KiteStringUtils.isEqual(provinceNbr, provinceZ) && !KiteStringUtils.isAnyEmpty(provinceNbr, provinceZ)) ||
                    (!KiteStringUtils.isEqual(provinceA, provinceZ) && !KiteStringUtils.isAnyEmpty(provinceA, provinceZ))) {
                    return true;
                }
            }

            // 互联网专线
            if(KiteStringUtils.isEqual(cateId, "2004029")) {
                // 受理人员工号归属省份与装机地址省份不一致，则认为是跨域
                if(!KiteStringUtils.isEqual(provinceNbr, provinceA) && !KiteStringUtils.isAnyEmpty(provinceNbr, provinceA)) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 获取工作日的偏移量
     * @param offerId 一个prodId对应多个offerId时，增加offerId区分
     * @return java.lang.String[]
     */
    public static String[] getWorkdayOffset(String prodId, String serviceOfferId, String offerId){
        String stype = "2021092314";
        String pkey = "workday";
        List<DcPublic> dcPublicList = DcPublicCache.getByPkey(stype, pkey);
        List<String> offSetList = new ArrayList<>();
        String[] offset = null;
        if(CollectionUtils.isEmpty(dcPublicList)){
            return offset;
        }

        // 将配置了 offerId 的排在前面
        dcPublicList.sort((t1, t2) -> {
            if(KiteStringUtils.isEmpty(t1.getCoded()) && KiteStringUtils.isNotEmpty(t2.getCoded())) {
                return 1;
            }
            return -1;
        });
        dcPublicList.forEach(dcPublic -> {
            if(dcPublic.getCodec().contains(prodId)
                && (KiteStringUtils.isAllEmpty(serviceOfferId,dcPublic.getCodee())||KiteStringUtils.equals(serviceOfferId,dcPublic.getCodee()))
                && (KiteStringUtils.isAnyEmpty(offerId, dcPublic.getCoded()) || KiteStringUtils.equals(offerId, dcPublic.getCoded()))){
                offSetList.add(dcPublic.getCodea());
                offSetList.add(dcPublic.getCodeb());
            }
        });
        offset = offSetList.stream().collect(Collectors.joining(",")).split(",");
        return offset;
    }
    public static String prodIdByProdId(String prodId){
        String stype = "2021092314";
        String pkey = "workday";
        AtomicReference<String> findProdId = new AtomicReference<>(StringUtils.EMPTY);
        List<DcPublic> dcPublicList = DcPublicCache.getByPkey(stype, pkey);
        dcPublicList.forEach(dcPublic -> {
            if(dcPublic.getCodec().contains(prodId)){
                findProdId.set(prodId);
            }
        });
        return findProdId.get();
    }
    public  String AZOffsetDay(String prodId,String date,String provinceCode){
        return AZOffsetDayOB( prodId, date, provinceCode,null);
    };
    public String wholeOffsetDay(String prodId,String date){
        return wholeOffsetDayOB(prodId,date,null);
    };
    /**
     * OB国际产品获取工作日
     * @param prodId
     * @param date
     * @return
     */
    public  String AZOffsetDayOB(String prodId,String date,String provinceCode,String serviceOfferId){
        infServiceBus =  SpringUtil.getBean(IInfServiceBus.class);
        if(null==date||null==prodId){
            date= KiteDateUtils.formatLocalDateTime(LocalDateTime.now(),"yyyy-MM-dd HH:mm");
        }
        LOGGER.info("查询偏移量的产品prodId========{}",prodId);
        String[] workdayOffset = getWorkdayOffset(prodId, serviceOfferId, null);
        if(workdayOffset.length>1){
            String offset = workdayOffset[1];
            provinceCode = StringUtils.isEmpty(provinceCode)?ContextUtil.getLoginInfo().getUserInfo().getPostProvinceNbr():provinceCode;
            UnicomRegion unicomRegion = UnicomRegionCache.getOneUnicomRegion(provinceCode);
            if (Objects.isNull(unicomRegion)) {
                unicomRegion = UnicomRegionCache.getOneUnicomRegion(ContextUtil.getLoginInfo().getUserInfo().getPostProvinceNbr());
            }
            JSONObject jsonObject = infServiceBus.qryHoliday(unicomRegion.getRegionName(),date,offset);
            if(null!=jsonObject){
                return null==jsonObject.get("DATA")?date:jsonObject.get("DATA").toString();
            }
        }
        return date;
    };

    public String wholeOffsetDayOB(String prodId,String date,String serviceOfferId){
        String offset = getWorkdayOffset(prodId, serviceOfferId, null)[0];
        return this.qryHoliday(date, offset);
    }

    public String wholeOffsetDayOB(String prodId, String date, String serviceOfferId, String offerId){
        String offset = getWorkdayOffset(prodId, serviceOfferId, offerId)[0];
        return this.qryHoliday(date, offset);
    }

    // 政企运营平台 工作日数据查询
    public String qryHoliday(String date, String offset){
        if(null == date){
            date = KiteDateUtils.formatLocalDateTime(LocalDateTime.now(),"yyyy-MM-dd HH:mm");
        }
        String provinceCode = ContextUtil.getLoginInfo().getUserInfo().getPostProvinceNbr();
        infServiceBus = SpringUtil.getBean(IInfServiceBus.class);
        JSONObject jsonObject = infServiceBus.qryHoliday(provinceCode, date, offset);
        if(null != jsonObject && !"B0001".equals(jsonObject.get("CODE")) && null != jsonObject.get("DATA")){
            date = jsonObject.get("DATA").toString();
        } else {
            // 接口没返回时直接加
            if(KiteStringUtils.isNotEmpty(offset)) {
                String[] arr = offset.split("\\.");
                LocalDateTime localDateTime = LocalDateTime.now().plusDays(Integer.valueOf(arr[0]));
                if(arr.length > 1) {
                    localDateTime = localDateTime.plusHours(Integer.valueOf(arr[1]) * 24 / 10);
                }
                date = KiteDateUtils.formatLocalDateTime(localDateTime, "yyyy-MM-dd HH:mm");
            }
        }
        return date;
    }

    public static String compareDate(CommonAttrVO attr, String prodId, String provinceCode ){
        String nowFinishTime = LocalAttrUtils.getInstance().AZOffsetDay(prodId, null,provinceCode);
        return compareDate(attr,nowFinishTime);
    }
    public static String compareDate(CommonAttrVO attr, String nowFinishTime){
        //String nowFinishTime = LocalAttrUtils.getInstance().AZOffsetDay(prodId, null,provinceCode);
        String origin = attr.getOriginValue();
        if(null==origin){
            origin=attr.getOldValue();
        }
        if(null==origin){
            return nowFinishTime;
        }
        if(DateFormatUtils.compareDate(origin, nowFinishTime, DateFormatUtils.DATE_MINUTE_FORMAT) < 0){
            return nowFinishTime;
        }else{
            return origin;
        }
    }
    public static String compareDate(KiteAttr attr, String prodId, String provinceCode ){
        String nowFinishTime = LocalAttrUtils.getInstance().AZOffsetDay(prodId, null,provinceCode);
        String origin = attr.getOriginValue();
        if(null==origin){
            origin=attr.getOldValue();
        }
        if(null==origin){
            return nowFinishTime;
        }
        if(DateFormatUtils.compareDate(origin, nowFinishTime, DateFormatUtils.DATE_MINUTE_FORMAT) < 0){
            return nowFinishTime;
        }else{
            return origin;
        }
    }
    /**
     * 获取结算账户
     * @return
     */
    public  List<JSONObject> qrySettlementAccount(){
        infServiceBus =  SpringUtil.getBean(IInfServiceBus.class);
        JSONObject jsonObject = infServiceBus.qrySettlementAccount(null);
        if(null==jsonObject.getJSONArray("DATA")){
            return new ArrayList<>();
        }
        List<JSONObject> data = jsonObject.getJSONArray("DATA").toJavaList(JSONObject.class);
        return data;
    }
    /**
     * 获取运营商
     * @return
     */
    public  List<JSONObject> operationPlatform(){
        infServiceBus =  SpringUtil.getBean(IInfServiceBus.class);
        JSONObject jsonObject = infServiceBus.operationPlatform();
        if(null==jsonObject.getJSONArray("DATA")){
            return new ArrayList<>();
        }
        List<JSONObject> data = jsonObject.getJSONArray("DATA").toJavaList(JSONObject.class);
        return data;
    }
    /**
     * 下级组织列表
     * @return
     */
    public  JSONObject queryGovEnterpriseOrg(String type,String value){
        if(Objects.isNull(type)){
            type = "3";//根据OA工号查询
        }
        infServiceBus =  SpringUtil.getBean(IInfServiceBus.class);
        JSONObject jsonObject = infServiceBus.queryGovEnterpriseOrg(type,value);
        return jsonObject;
    }
    /**
     * 下级组织列表
     * @return
     */
    public  JSONObject queryOrgInfo(String orgCode,String provinceCode,String cityCode,String level){
        infServiceBus =  SpringUtil.getBean(IInfServiceBus.class);
        JSONObject jsonObject = infServiceBus.queryOrgInfo(orgCode,provinceCode,cityCode,level);
        return jsonObject;
    }
    /**
     * 获取POP点
     * @return
     */
    public  List<JSONObject> qryPopData(String countryCode){
        infServiceBus =  SpringUtil.getBean(IInfServiceBus.class);
        JSONObject jsonObject = infServiceBus.qryPopData(countryCode);
        if(null==jsonObject.getJSONArray("DATA")){
            return new ArrayList<>();
        }
        List<JSONObject> data = jsonObject.getJSONArray("DATA").toJavaList(JSONObject.class);
        return data;
    }
    /**
     * 全程要求完成时间位移date天
     * @param date
     * @return
     */
    public static String wholeOffsetDay(int date){
        LocalDateTime now = LocalDateTime.now().plusDays(date);
       return KiteDateUtils.formatLocalDateTime(now,DateFormatUtils.DATE_MINUTE_FORMAT);
    };

    /**
     * 处理跨域核查的属性
     * @param isCrossDomain
     * @param mainServiceOfferId
     * @param checkWayAttr
     * @param value
     * @param prodId
     */
    public static void ORD10222(boolean isCrossDomain,String mainServiceOfferId,KiteAttr checkWayAttr,String value,String prodId){
        if (isCrossDomain) {
            if (KiteStringUtils.equals(mainServiceOfferId, LocalServiceOfferConsts.SERVICE_OFFER_RESOURCE_CHECK)) {
                if (LocalAttrUtils.LOCAL_PROD.contains(prodId)) {
                    checkWayAttr.setValue("1");
                    checkWayAttr.setValueDesc("精准串行核查");
                } else {
                    checkWayAttr.setShowType(KeyConsts.PROD_ATTR_SHOW_TYPE_H);
                    checkWayAttr.setValue("2");
                    checkWayAttr.setValueDesc("快速并行核查");
                }
            }
            if (KiteStringUtils.equalsAny(mainServiceOfferId, ServiceOfferConsts.SERVICE_OFFER_ORDER, ServiceOfferConsts.SERVICE_OFFER_MODIFY)) {
                if (KiteStringUtils.equalsAny(value, "2", "1")) {
                    checkWayAttr.setShowType(KeyConsts.PROD_ATTR_SHOW_TYPE_H);
                    if (LocalAttrUtils.LOCAL_PROD.contains(prodId)) {
                        checkWayAttr.setValue("1");
                        checkWayAttr.setValueDesc("精准串行核查");
                    } else {
                        checkWayAttr.setValue("2");
                        checkWayAttr.setValueDesc("快速并行核查");
                    }

                } else {
                    checkWayAttr.setShowType(KeyConsts.PROD_ATTR_SHOW_TYPE_E);
                }
            }
        }else{
            if (KiteStringUtils.equalsAny(mainServiceOfferId,ServiceOfferConsts.SERVICE_OFFER_ORDER,ServiceOfferConsts.SERVICE_OFFER_MODIFY)) {
                checkWayAttr.setShowType(KeyConsts.PROD_ATTR_SHOW_TYPE_E);
            }
            if (mainServiceOfferId.equals(LocalServiceOfferConsts.SERVICE_OFFER_RESOURCE_CHECK)) {
                checkWayAttr.setShowType(KeyConsts.PROD_ATTR_SHOW_TYPE_D);
            }
        }
    }
    public  static KiteAttrValue pleaseSelect(){
        KiteAttrValue kiteAttrValue0 = new KiteAttrValue();
        kiteAttrValue0.setAttrValue("");
        kiteAttrValue0.setAttrId("19700101");
        kiteAttrValue0.setAttrValueName("--请选择--");
        kiteAttrValue0.setSortBy("0");
        return  kiteAttrValue0;
    }
    /**
     * 获取五大双线分类ID
     * @return
     */
    public static List<String> getDoubleLineCateIds() {
        List<String> cateIds = new ArrayList<>();
        List<DcPublic> dcPublicList = new ArrayList<>();
        Optional.ofNullable(DcPublicCache.getByPcode("2108161001", "WDSX_CATE_ID")).ifPresent(dcPublicList::addAll);
        if (KiteListUtils.isNotEmpty(dcPublicList)) {
            dcPublicList.forEach(dcPublic -> {
                Optional.ofNullable(dcPublic.getCodea()).ifPresent(cateIds::add);
            });
        }
        return cateIds;
    }
    public static String FormatByValue(String value){
        int le = value.length();
       return DateFormatUtils.DATE_TIME_FORMAT.substring(0,le);
    }
}
